# coding: utf-8
import base64

from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QImage
from PySide6.QtWidgets import QVBoxLayout, QWidget, QLineEdit, QHBoxLayout
from qeventmanager import qevent_manager
from qfluentwidgets import LineEdit, PasswordLineEdit, Action, FluentIcon as FIF, PrimaryPushButton, CheckBox, \
    HyperlinkLabel, BodyLabel, setFont

from api import LoginCodeAPI, LoginAPI
from common import cfg, signalBus
from components import ImageLabel, Alert


class UIUserLoginWidget:
    """
    账号密码登录组件 UI
    """

    def setupUi(self, Form) -> None:
        """
        初始化组件
        """
        self.verticalLayout = QVBoxLayout(Form)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout_2 = QHBoxLayout()
        self.usernameLineEdit = LineEdit(Form)
        self.passwordLineEdit = PasswordLineEdit(Form)
        self.captchaLineEdit = LineEdit(Form)
        self.codeLabel = ImageLabel(Form)
        self.checkBox = CheckBox("阅读并同意", Form)
        self.userBtn = HyperlinkLabel(QUrl('https://service.qsxt.info/qsxt_yhxy.html'), "<用户协议>", Form)
        self.separationLabel = BodyLabel("和", Form)
        self.privacyBtn = HyperlinkLabel(QUrl('https://service.qsxt.info/qsxt_yszc.html'), "<隐私政策>", Form)
        self.loginButton = PrimaryPushButton("登录", Form)

        self.__initWidget()
        self.__initLayout()

    def __initWidget(self) -> None:
        """
        初始化组件
        """
        self.usernameLineEdit.addAction(Action(FIF.PEOPLE, "", self.usernameLineEdit),
                                        QLineEdit.ActionPosition.LeadingPosition)
        self.passwordLineEdit.addAction(Action(FIF.VPN, "", self.passwordLineEdit),
                                        QLineEdit.ActionPosition.LeadingPosition)
        self.captchaLineEdit.addAction(Action(FIF.PHOTO, "", self.captchaLineEdit),
                                       QLineEdit.ActionPosition.LeadingPosition)

        self.codeLabel.setFixedSize(100, 40)
        self.usernameLineEdit.setFixedHeight(40)
        self.passwordLineEdit.setFixedHeight(40)
        self.captchaLineEdit.setFixedHeight(40)

        self.checkBox.setChecked(True)

        self.usernameLineEdit.setPlaceholderText("用户名")
        self.passwordLineEdit.setPlaceholderText("密码")
        self.captchaLineEdit.setPlaceholderText("验证码")

        self.usernameLineEdit.setClearButtonEnabled(True)
        self.passwordLineEdit.setClearButtonEnabled(True)
        self.captchaLineEdit.setClearButtonEnabled(True)
        self.passwordLineEdit._adjustTextMargins()

        self.codeLabel.setText("获取验证码")
        setFont(self.codeLabel, 14)

    def __initLayout(self) -> None:
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setSpacing(20)
        self.verticalLayout.addWidget(self.usernameLineEdit)
        self.verticalLayout.addWidget(self.passwordLineEdit)
        self.horizontalLayout.addWidget(self.captchaLineEdit)
        self.horizontalLayout.addWidget(self.codeLabel)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.horizontalLayout_2.setSpacing(5)
        self.horizontalLayout_2.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout_2.addWidget(self.checkBox)
        self.horizontalLayout_2.addWidget(self.userBtn)
        self.horizontalLayout_2.addWidget(self.separationLabel)
        self.horizontalLayout_2.addWidget(self.privacyBtn)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

        self.verticalLayout.addWidget(self.loginButton)
        self.verticalLayout.addStretch(1)


class UserLoginWidget(QWidget, UIUserLoginWidget):
    """
    账号密码登录组件
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.sessionId = ''

        username = cfg.get(cfg.username)
        if username:
            self.usernameLineEdit.setText(username)
            self.passwordLineEdit.setText(cfg.get(cfg.password))

        self.__connectSignals()

    def __connectSignals(self) -> None:
        """
        信号连接
        :return:
        """
        self.codeLabel.clicked.connect(self.onGetCode)
        self.loginButton.clicked.connect(self.onLogin)

    def onGetCode(self) -> None:
        """
        获取验证码
        :return:
        """
        username = self.usernameLineEdit.text()
        if not username:
            Alert.warning("请输入用户名")
            return
        qevent_manager.addTask(LoginCodeAPI.getValidationCode, username, 3, slot=self.setCodeImage)

    def setCodeImage(self, result: dict) -> None:
        """
        设置验证码图片
        :param result:
        :return:
        """
        print(result)
        data = result.get('data', {})
        code = data.get('code')
        self.sessionId = data.get('sessionId')
        image = QImage.fromData(base64.b64decode(code))
        self.codeLabel.setImage(image)

    def onLogin(self) -> None:
        """
        登录
        :return:
        """
        username = self.usernameLineEdit.text()
        password = self.passwordLineEdit.text()
        captcha = self.captchaLineEdit.text()
        if not username:
            Alert.warning("请输入用户名")
            return
        if not password:
            Alert.warning("请输入密码")
            return
        if not captcha:
            Alert.warning("请输入验证码")
            return
        if not self.checkBox.isChecked():
            Alert.warning("请阅读并同意用户协议和隐私政策")
            return
        cfg.set(cfg.username, username)
        cfg.set(cfg.password, password)
        qevent_manager.addTask(LoginAPI.login, username, password, captcha, self.sessionId, slot=self.onLoginResult)

    def onLoginResult(self, result: dict) -> None:
        LoginAPI.setCookies(result)
        signalBus.loginSuccessSignal.emit()
